package com.anntly.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: 张文
 * @Date: 2020/5/5 15:24
 * @Description: 1. 自定义Handler，实现 ChannelInboundHandlerAdapter
 * 2.
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * @return void
     * @Description 读取客户端的数据
     * @Date 2020/5/5 15:26
     * @Param [ctx, msg] ctx:上下文对象，可以回去Pipeline、channel、地址等
     * msg:客户端发送的数据，默认为Object
     **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        StudentPOJO.Student student = (StudentPOJO.Student) msg;
        System.out.println("客户端数据:" + student.getId() + ":" + student.getName());
    }

    /**
     * @return void
     * @Description 数据读取完毕后的处理
     * @Date 2020/5/5 15:29
     * @Param [ctx]
     **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 将数据写入到缓存并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8));
    }

    /**
     * @return void
     * @Description 处理异常，一般需要关闭通道
     * @Date 2020/5/5 15:31
     * @Param [ctx, cause]
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
